package com.breakfast.fun.ui.home;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.breakfast.fun.App;
import com.breakfast.fun.R;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.CustomDialog;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallListener;
import com.fm.openinstall.model.AppData;
import com.fm.openinstall.model.Error;

import java.util.Arrays;

public abstract class PermissionActivity extends AppCompatActivity implements AppInstallListener {

    private static final int REQUEST_CODE = 1;
    private CustomDialog mDialog;
    private int showDialog = 0;
    private String permisstions[] = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
    private boolean isNeedShow = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        OpenInstall.getInstall(this, this);
        //检测有没必要权限。获取。跳转
        if (Build.VERSION.SDK_INT >= 23) {
            //检测权限
            int write_permission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int location_permission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION);


            //1、检测没有存储卡权限，请求。
            //2、第二次进入检测已经有存储卡权限，下载。
            if (write_permission != PackageManager.PERMISSION_GRANTED && location_permission != PackageManager.PERMISSION_GRANTED) {
                L.d("第一检测，请求系统权限");
                ActivityCompat.requestPermissions(PermissionActivity.this, permisstions,
                        REQUEST_CODE);
            } else {
                initView();
            }
        } else {
            initView();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] requestPermissions, @NonNull int[] grantResults) {
        //存储卡权限，定位权限，permissions
        //循环判断permissions中的权限，没有
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//存储卡授权成功，跳转
//                    T.show("授权成功");
                    L.d("授权成功");
                    initView();
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {//点击拒绝授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {//点击拒绝，再次弹出
                        L.d("再次弹出");
                        if (mDialog == null || !mDialog.isShowing()) {
                            mDialog = new CustomDialog(PermissionActivity.this, R.style.dialog_style,
                                    R.layout.dialog_custom, "请允许获得访问存储权限", "早范无法获得访问存储权限,可能无法正常更新。", false, true, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mDialog.dismiss();
                                    ActivityCompat.requestPermissions(PermissionActivity.this, permisstions,
                                            REQUEST_CODE);
                                }
                            });
                            mDialog.show();
                        }
                    } else { // 选择不再询问，并点击拒绝，弹出自定义提示框，引导用户自己授权
                        if (mDialog == null || !mDialog.isShowing()) {
                            mDialog = new CustomDialog(PermissionActivity.this, R.style.dialog_style,
                                    R.layout.dialog_custom, "请允许获得访问存储权限", "早范无法获得访问存储权限，点击确定手动开启权限。系统设置->早范->权限管理", false, true, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mDialog.dismiss();
                                    Intent localIntent = new Intent();
                                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    if (Build.VERSION.SDK_INT >= 9) {
                                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                                    } else if (Build.VERSION.SDK_INT <= 8) {
                                        localIntent.setAction(Intent.ACTION_VIEW);
                                        localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                                        localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                                    }
                                    startActivity(localIntent);
                                    isNeedShow = true;
                                }
                            });
                            mDialog.show();
                        }

                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, requestPermissions, grantResults);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDialog != null) {
            if (mDialog.isShowing()) {
                isNeedShow = false;
            } else {
                isNeedShow = true;
            }
        }
    }

    @Override
    protected void onResume() {
        if (Build.VERSION.SDK_INT >= 23) {

            if (isNeedShow) {
                //检测权限
                int write_permission = ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
                int location_permission = ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION);


                //1、检测没有存储卡权限，请求。
                //2、第二次进入检测已经有存储卡权限，下载。
                if (write_permission != PackageManager.PERMISSION_GRANTED && location_permission != PackageManager.PERMISSION_GRANTED) {
                    L.d("第一检测，请求系统权限");
                    ActivityCompat.requestPermissions(PermissionActivity.this, permisstions,
                            REQUEST_CODE);
                } else {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    initView();
                }
            }
        } else {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            initView();
        }

        super.onResume();
    }

    public abstract void initView();


    @Override
    public void onInstallFinish(AppData appData, Error error) {
        if (error == null) {
            String localCode = "";
            String localData = "";
            L.d("Permission : OpenInstall install-data : " + appData.toString());
            if (!appData.getChannel().isEmpty()) {
                localCode = appData.getChannel();
                HomeFragment.localCode = localCode;
                //将此邀请码存入本地，在注册时候判断有没手动填写邀请码，没有则以此作为邀请码上传。
            }
            if (!appData.getData().isEmpty()) {
                localCode = appData.getData();
            }

        } else {
            L.d("Permission : error : " + error.toString());
        }
    }

}
